<template>
    <view>
        <image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
            mode="aspectFill"></image>
        <u-navbar :title="isViewMode ? '查看土壤检测标准' : '检验标准制定'" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
            :titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder>
        </u-navbar>

        <view class="content">
            <!-- 筛选区 -->
            <view class="card filters">
                <view class="row">
                    <text class="label">监测年份</text>
                    <view class="range">
                        <picker mode="date" fields="year" :value="filters.monitorYear" @change="onmonitorYearChange">
                            <view class="picker-input" :class="{ placeholder: !filters.monitorYear }">
                                {{ filters.monitorYear || '请选择' }}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="row">
                    <text class="label">监测类别</text>
                    <view class="row-main">
                        <uni-data-select class="select" v-model="filters.category" :localdata="categoryOptions" clear
                            placeholder="全部" />
                    </view>
                </view>
                <view class="row">
                    <text class="label">级&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</text>
                    <view class="row-main">
                        <uni-data-select class="select disabled" v-model="filters.level" :localdata="levelOptions" 
                            placeholder="请选择级别" :disabled="true" />
                    </view>
                </view>
                <view class="row" v-if="!isViewMode">
                    <view class="bg colfff file-upload-btn"
                        style="border: 1rpx solid #229246; border-radius: 10rpx; padding: 10rpx 20rpx;"
                        @click="handleFileUpload">
                        选择文件
                    </view>
                </view>

                <!-- 已选择文件列表 -->
                <view v-if="uploadedFiles.length > 0" class="file-list">
                    <view v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
                        <view class="file-info">
                            <u-icon name="file-text" size="32" color="#007AFF"></u-icon>
                            <text class="file-name">{{ file.name }}</text>
                            <text class="file-size">{{ formatSize(file.size) }}</text>
                        </view>
                        <view class="file-status">
                            <text v-if="file.status === 'success'" class="status-success">{{ getStatusText(file.status)
                                }}</text>
                            <text v-else-if="file.status === 'progress'" class="status-progress">{{
                                getStatusText(file.status) }} {{ file.progress }}%</text>
                            <text v-else-if="file.status === 'fail'" class="status-fail">{{ getStatusText(file.status)
                                }}</text>
                            <text v-else class="status-pending">{{ getStatusText(file.status) }}</text>
                        </view>
                        <u-icon name="close" size="24" color="#999" @click="removeFile(index)"></u-icon>
                    </view>
                </view>

            </view>
            <!-- 列表区 -->
            <view class="list">
                <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20 pb-20" v-for="(item, index) in table" :key="item.id || index">
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">检测项目</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item.testItem" placeholder="请输入检测项目" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">风险筛选值pH≤5.5</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item.le55" placeholder="请输入数值" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">风险筛选值5.5&lt;pH≤6.5</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item._55to65" placeholder="请输入数值" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">风险筛选值6.5&lt;pH≤7.5</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item._65to75" placeholder="请输入数值" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">风险筛选值pH&gt;7.5</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item.g75" placeholder="请输入数值" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">检测方法</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item.testMethod" placeholder="请输入检测方法" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rows rowsm mb-20 input-row">
                        <view class="col666 label">判定依据</view>
                        <view class="col666 ml-10 mr-10">:</view>
                        <view class="fs-28 one_overflow input-container">
                            <input v-model="item.testStandard" placeholder="请输入判定依据" class="input-field" :disabled="isViewMode" />
                        </view>
                    </view>
                    <view class="fs-28 rowsb rowsm mb-20" v-if="!isViewMode">
                        <view class="colfff bg w-200 h-60 br-10 rowsc rowsm" @click="addCard(index)">添加</view>
                        <view class="colfff bg w-200 h-60 br-10 rowsc rowsm" @click="removeCard(index)">删除</view>
                    </view>
                </view>
            </view>
        </view>
        <view v-if="!isViewMode" @tap="submit('publish')" class="w-300 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;left: 30rpx;">
            确定
        </view>
        <view v-if="!isViewMode" @tap="submit('draft')" class="w-300 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;right: 30rpx;">
            存草稿
        </view>
        <!-- lsj-upload 插件 -->
        <lsj-upload ref="lsjUploadRef"></lsj-upload>
    </view>
</template>

<script>
import { typeSoil, levelSoil, uploadFile, generateStandardTable, addSoilStandard, getSoilStandardDetailList, updateSoilStandard } from '@/api/soil'
import navbarMixin from '@/common/navbarMixin'
import config from '@/config'
export default {
    mixins: [navbarMixin],
    data () {
        return {
            isViewMode: false, // 是否为查看模式
            filters: {
                monitorYear: '',
                category: '',
                level: ''
            },
            categoryOptions: [],
            levelOptions: [],
            uploadedFiles: [], // 上传的文件列表
            table: [{
                id: Date.now(),
                testItem: '',
                le55: '',
                _55to65: '',
                _65to75: '',
                g75: '',
                testMethod: '',
                testStandard: ''
            }]
        }
    },
    onLoad(options) {
        this.typeSoil()
        this.levelSoil()
        this.getUserInfo()
        
        // 检查是否是查看详情模式或编辑模式
        if (options.monitorYear && options.monitorType && options.level) {
            // 根据URL参数判断是否为查看模式（可以通过添加view参数来区分）
            this.isViewMode = options.view === 'true'
            this.filters.monitorYear = options.monitorYear
            this.filters.category = options.monitorType
            this.filters.level = options.level
            this.loadDetailData()
        }
    },
    onShow() {
        this.getUserInfo();
    },
    methods: {
        getUserInfo() {
            this.$store.dispatch('GetInfo').then(res => {
                // 设置用户级别到筛选条件
                this.filters.level = res.user.dept.deptLevel
            }).catch(error => {
                console.log('获取用户信息失败，错误信息:', error)
            })
        },
        // 加载详情数据
        loadDetailData() {
            const params = {
                monitorYear: this.filters.monitorYear,
                monitorType: this.filters.category,
                level: this.filters.level
            }
            
            getSoilStandardDetailList(params).then(res => {
                console.log('获取详情数据:', res)
                if (res.rows && res.rows.length > 0) {
                    // 按照ID排序，确保数据顺序一致
                    const sortedRows = res.rows.sort((a, b) => (a.id || 0) - (b.id || 0))
                    // 使用与PC端相同的数据解析方式
                    this.table = this.normalizeRiskFields(sortedRows)
                }
            }).catch(error => {
                console.error('获取详情数据失败:', error)
                uni.showToast({
                    title: '获取详情数据失败',
                    icon: 'none'
                })
            })
        },
        // 解析风险筛选值字段（与PC端保持一致）
        normalizeRiskFields(rows) {
            return rows.map(row => {
                // 如果存在 riskScreeningValue 字段，解析 JSON 字符串
                if (row.riskScreeningValue) {
                    try {
                        const riskData = typeof row.riskScreeningValue === 'string'
                            ? JSON.parse(row.riskScreeningValue)
                            : row.riskScreeningValue

                        // 将解析出的风险筛选值合并到行数据中，null值转换为空字符串用于显示
                        return {
                            ...row,
                            testItem: row.testItem || '',
                            testMethod: row.testMethod || '',
                            testStandard: row.testStandard || '',
                            le55: riskData.le55 || '',
                            _55to65: riskData._55to65 || '',
                            _65to75: riskData._65to75 || '',
                            g75: riskData.g75 || ''
                        }
                    } catch (error) {
                        console.error('解析风险筛选值失败:', error, row.riskScreeningValue)
                        return {
                            ...row,
                            testItem: row.testItem || '',
                            testMethod: row.testMethod || '',
                            testStandard: row.testStandard || '',
                            le55: '',
                            _55to65: '',
                            _65to75: '',
                            g75: ''
                        }
                    }
                }
                return {
                    ...row,
                    testItem: row.testItem || '',
                    testMethod: row.testMethod || '',
                    testStandard: row.testStandard || '',
                    le55: '',
                    _55to65: '',
                    _65to75: '',
                    g75: ''
                }
            })
        },
        // 生成土壤监测标准表
        generateStandardTable(data) {
            generateStandardTable(data).then(res => {
                console.log('生成土壤监测标准表:', res)
                if (res.data && res.data.length > 0) {
                    // 按照ID排序，确保数据顺序一致
                    const sortedData = res.data.sort((a, b) => (a.id || 0) - (b.id || 0))
                    this.table = sortedData
                } else {
                    this.table = res.data || []
                }
            })
        },
        // 获取监测级别
        levelSoil() {
            levelSoil().then(res => {
                this.levelOptions = res.data.map(item => ({
                    value: item.dictValue,
                    text: item.dictLabel
                }))
            })
        },
        // 获取监测类型
        typeSoil() {
            typeSoil().then(res => {
                this.categoryOptions = res.data.map(item => ({
                    value: item.dictValue,
                    text: item.dictLabel
                }))
            })
        },
        // 监测年份选择
        onmonitorYearChange(e) {
            this.filters.monitorYear = (e.detail && e.detail.value) || ''
        },
        // 搜索
        onSearch() {
            console.log('搜索条件:', this.filters)
        },
        // 重置
        onReset() {
            this.filters = {
                monitorYear: '',
                category: '',
                level: ''
            }
        },
        // 文件上传
        handleFileUpload() {
            this.$refs.lsjUploadRef.chooseFile({
                count: 5, // 最多选择5个文件
                size: 10, // 单个文件最大10MB
                multiple: true, // 允许多选
                formats: 'xlsx,xls,docx,pdf', // 只允许选择指定格式
                success: (files) => {
                    // 将新选择的文件添加到现有文件列表
                    this.uploadedFiles = [...this.uploadedFiles, ...files]
                    // 自动上传文件
                    this.autoUploadFiles(files)
                },
                fail: (error) => {
                    uni.showToast({
                        title: '选择文件失败',
                        icon: 'none'
                    })
                }
            })
        },
        // 自动上传文件
        autoUploadFiles(newFiles) {
            newFiles.forEach(file => {
                this.uploadFile(file)
            })
        },
        // 使用 lsj-upload 插件的上传方法
        uploadFile(file) {
            this.$refs.lsjUploadRef.upload({
                file: file,
                url: `${config.baseUrl}/file/upload`, // 上传接口地址
                name: 'file', // 文件字段名
                method: 'post',
                header: {
                    'Authorization': 'Bearer ' + uni.getStorageSync('App-Token')
                },
                formData: {
                    // 额外的表单数据
                },
                onprogress: (e) => {
                    file.status = 'progress'
                    file.progress = e.progress || 0
                },
                success: (e) => {
                    file.status = 'success'
                    
                    // 解析上传结果，提取 name 和 url
                    try {
                        const result = JSON.parse(e.result)
                        console.log('上传结果:', result)
                        // 上传成功后生成土壤监测标准表
                        this.generateStandardTable(result)
                    } catch (error) {
                    }
                    uni.showToast({
                        title: '文件上传成功',
                        icon: 'success'
                    })
                },
                fail: (e) => {
                    file.status = 'fail'
                    uni.showToast({
                        title: '文件上传失败',
                        icon: 'none'
                    })
                }
            })
        },
        removeFile(index) {
            if (this.uploadedFiles && index > -1 && index < this.uploadedFiles.length) {
                // 从数组中移除
                this.uploadedFiles.splice(index, 1)
                // 重新赋值触发视图更新
                this.uploadedFiles = [...this.uploadedFiles]
            }
        },
        // 格式化文件大小
        formatSize(n) {
            if (!n && n !== 0) return ''
            const kb = n / 1024,
                mb = kb / 1024
            return mb >= 1 ? (mb.toFixed(1) + ' MB') : (Math.max(kb, 1).toFixed(0) + ' KB')
        },
        // 获取状态文本
        getStatusText(status) {
            switch (status) {
                case 'progress':
                    return '上传中'
                case 'success':
                    return '成功'
                case 'fail':
                    return '失败'
                default:
                    return '待上传'
            }
        },
        // 添加卡片
        addCard(index) {
            // 生成一个临时的负数ID，确保新卡片不会影响现有数据的排序
            const newCard = {
                id: -(Date.now() + Math.random()), // 使用负数ID，确保不影响排序
                testItem: '',
                le55: '',
                _55to65: '',
                _65to75: '',
                g75: '',
                testMethod: '',
                testStandard: ''
            }
            // 在指定索引后插入新卡片
            this.table.splice(index + 1, 0, newCard)
        },
        // 删除卡片
        removeCard(index) {
            if (this.table.length > 1) {
                this.table.splice(index, 1)
            } else {
                uni.showToast({
                    title: '至少保留一个卡片',
                    icon: 'none'
                })
            }
        },
        // 提交表单
        submit(status = 'publish') {
            // 验证表单数据
            const hasValidData = this.table.some(item => 
                item.testItem || item.le55 || item._55to65 || item._65to75 || item.g75 || item.testMethod || item.testStandard
            )
            
            if (!hasValidData) {
                uni.showToast({
                    title: '请填写至少一个卡片的数据',
                    icon: 'none'
                })
                return
            }
            
            // 验证筛选条件
            if (!this.filters.monitorYear) {
                uni.showToast({
                    title: '请选择监测年份',
                    icon: 'none'
                })
                return
            }
            
            if (!this.filters.category) {
                uni.showToast({
                    title: '请选择监测类别',
                    icon: 'none'
                })
                return
            }
            
            if (!this.filters.level) {
                uni.showToast({
                    title: '请选择监测级别',
                    icon: 'none'
                })
                return
            }
            
            // 根据是否为编辑模式决定调用哪个API
            const isEditMode = !this.isViewMode && (this.filters.monitorYear && this.filters.category && this.filters.level)
            
            // 构建提交数据 - 与PC端保持一致的数据结构
            const submitData = this.table.map(item => {
                // 提取风险筛选值4项并合成JSON串
                const riskScreeningValue = {
                    le55: item.le55 || null,
                    _55to65: item._55to65 || null,
                    _65to75: item._65to75 || null,
                    g75: item.g75 || null
                }

                const data = {
                    monitorYear: Number(this.filters.monitorYear),
                    monitorType: this.filters.category,
                    level: this.filters.level,
                    testItem: item.testItem || null,
                    testStandard: item.testStandard || null,
                    testMethod: item.testMethod || null,
                    riskScreeningValue: JSON.stringify(riskScreeningValue),
                    status: status
                }

                // 编辑模式下，如果行数据有id，则保留id用于更新
                if (isEditMode && item.id) {
                    data.id = item.id
                }

                return data
            })
            
            console.log('提交数据:', submitData)
            
            // 调用API提交数据
            const apiCall = isEditMode ? updateSoilStandard : addSoilStandard
            apiCall(submitData).then(res => {
                console.log('提交结果:', res)
                const actionText = isEditMode ? '修改' : (status === 'publish' ? '发布' : '草稿保存')
                uni.showToast({
                    title: `${actionText}成功`,
                    icon: 'success'
                })
                // 修改成功后返回上一页
                if (isEditMode) {
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                }
            }).catch(error => {
                console.error('提交失败:', error)
                const actionText = isEditMode ? '修改' : (status === 'publish' ? '发布' : '草稿保存')
                uni.showToast({
                    title: `${actionText}失败`,
                    icon: 'none'
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.theme-green {
    --brand: #29a74d;
    --brand-weak: rgba(41, 167, 77, 0.12);
    --brand-press: #229246;
}

.page {
    background: #f6f7fb;
    min-height: 100vh;
    @extend .theme-green;
}

.content {
    padding: 40rpx 20rpx;
}

/* 卡片通用样式 */
.card {
    background: #fff;
    border-radius: 18rpx;
    padding: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    border: 1rpx solid #eef2ef;
}

/* 筛选区 */
.filters {
    margin-bottom: 20rpx;

    .row {
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;

        &:last-child {
            margin-bottom: 0;
        }

        .label {
            color: #2c3e2f;
            font-size: 30rpx;
            margin-right: 10rpx;
        }

        .range {
            flex: 1;
            display: grid;
            grid-template-columns: 1fr auto 1fr;
            column-gap: 20rpx;
            align-items: center;
        }

        .picker-input {
            width: 100%;
            min-width: 0;
            box-sizing: border-box;
            height: 60rpx;
            line-height: 60rpx;
            background: #f6fbf8;
            border-radius: 10rpx;
            padding: 0 24rpx;
            color: #111;
            font-size: 32rpx;
            border: 1rpx solid rgba(41, 167, 77, 0.25);

            &.placeholder {
                color: #89a08f;
            }
        }

        .range>picker {
            width: 100%;
            display: block;
        }

        .row-main {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 0;
        }

        .select {
            flex: 1;
            --height: 68rpx;

            :deep(.uni-data-checklist) {
                background: #f6fbf8;
                border-radius: 10rpx;
            }

            :deep(.uni-select) {
                border: 1rpx solid rgba(41, 167, 77, 0.25);
                background: #f6fbf8;
                height: 88rpx;
                border-radius: 14rpx;
            }

            :deep(.uni-select__input) {
                min-height: 88rpx;
                line-height: 88rpx;
                padding-right: 56rpx;
            }

            :deep(.uni-select__input-text) {
                font-size: 32rpx;
            }

            :deep(.uni-select .uni-icons),
            :deep(.uni-icons.uniui-clear),
            :deep(.uniui-clear) {
                font-size: 38rpx !important;
            }
            
            // 禁用状态样式
            &.disabled {
                :deep(.uni-select) {
                    background: #f5f5f5;
                    border-color: #d9d9d9;
                    color: #999;
                }
                
                :deep(.uni-select__input-text) {
                    color: #999;
                }
            }
        }

        .action {
            height: 60rpx;
            line-height: 60rpx;
            padding: 0 20rpx;
            background: var(--brand-weak);
            color: #16723a;
            border-radius: 14rpx;
            font-size: 32rpx;
            min-width: 160rpx;
            margin-left: 32rpx;
            border: 1rpx solid rgba(41, 167, 77, 0.25);

            &.primary {
                background: var(--brand);
                color: #fff;
                border-color: var(--brand);

                &:active {
                    background: var(--brand-press);
                }
            }
        }
    }
}

.mine-navbar-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 2;
}

/* 文件上传相关样式 */
.file-upload-btn {
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:active {
        opacity: 0.8;
        transform: scale(0.98);
    }
}

.file-list {
    margin-top: 20rpx;
}

.file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    margin-bottom: 12rpx;
}

.file-info {
    display: flex;
    align-items: center;
    flex: 1;
    gap: 12rpx;
}

.file-name {
    font-size: 26rpx;
    color: #333;
    flex: 1;
}

.file-size {
    font-size: 24rpx;
    color: #999;
}

.file-status {
    margin-right: 16rpx;
}

.status-success {
    font-size: 24rpx;
    color: #4caf50;
}

.status-progress {
    font-size: 24rpx;
    color: #2196f3;
}

.status-fail {
    font-size: 24rpx;
    color: #f44336;
}

.status-pending {
    font-size: 24rpx;
    color: #999;
}

/* 输入行样式 */
.input-row {
    display: flex;
    align-items: center;
    
    .label {
        width: 200rpx;
        flex-shrink: 0;
        text-align: left;
    }
    
    .col666.ml-10.mr-10 {
        width: 20rpx;
        flex-shrink: 0;
        text-align: center;
    }
}

/* 输入框容器样式 */
.input-container {
    flex: 1;
    display: flex;
    align-items: center;
}

/* 输入框样式 */
.input-field {
    width: 100%;
    height: 60rpx;
    line-height: 60rpx;
    background: #f6fbf8;
    border: 1rpx solid rgba(41, 167, 77, 0.25);
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
    
    &::placeholder {
        color: #89a08f;
    }
    
    &:focus {
        border-color: #29a74d;
        background: #fff;
    }
    
    &:disabled {
        background: #f5f5f5;
        border-color: #d9d9d9;
        color: #999;
        cursor: not-allowed;
    }
}
</style>